package com.leijie.zerocopy;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author LeiJie
 * @time 2020-5-15 17:47
 * @desc TODO
 */
public class NewIOServer {

    public static void main(String[] args) throws Exception{
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        ServerSocket serverSocket = serverSocketChannel.socket();
        serverSocket.setReuseAddress(true);
        serverSocket.bind(new InetSocketAddress(8899));

        ByteBuffer buffer = ByteBuffer.allocate(4096);
        while (true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(true);

            int totalCount = 0;
            int readCount = 0;

            while (readCount != -1){
                try {
                    readCount = socketChannel.read(buffer);
                    totalCount += readCount;
                }catch (Exception e){
                    e.printStackTrace();
                }
                buffer.rewind();
            }
            System.out.println("接受总字节数："+totalCount);
        }
    }

}
